package com.hyt.it.ogt.pj.data.service.pj.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.hyt.core.base.BaseServiceImpl;
import com.hyt.it.ogt.pj.data.common.MarkConfigProperties;
import com.hyt.it.ogt.pj.data.common.ResponseCode;
import com.hyt.it.ogt.pj.data.exception.MarkException;
import com.hyt.it.ogt.pj.data.mapper.pj.ConfigMapper;
import com.hyt.it.ogt.pj.data.model.entity.pj.Config;
import com.hyt.it.ogt.pj.data.service.pj.IConfigService;

/**
 * <p>
 * 评卷参数表 服务实现类
 * </p>
 *
 * @author liuqi
 * @date 2022-06-07
 */
@Service
public class ConfigServiceImpl extends BaseServiceImpl<ConfigMapper, Config> implements IConfigService {

    @Autowired
    private MarkConfigProperties properties;

	@Override
	public Config selectByLabel(String projectId, String label) {
		return this.lambdaQuery()
				.eq(Config::getProjectId, projectId)
				.eq(Config::getParam, label)
				.one();
	}

    @Override
    public List<Config> findProjectConfigs(String projectId) {
        List<Config> configs = this.lambdaQuery()
				.eq(Config::getProjectId, projectId)
				.list();
        return configs;
    }

    @Override
    public Integer initMarkParam(String projectId) throws Exception {
        // 查询数据库查看该评卷项目的评卷参数是否已经初始化过
        List<Config> configs = this.findProjectConfigs(projectId);
		if (CollectionUtils.isEmpty(configs)) {
			// 从配置文件中读取评卷参数
			List<Config> newConfigs = new ArrayList<>();
			configs = properties.getConfigs();
			for (Config config : configs) {
				Config con = new Config();
				con.setProjectId(projectId);
				con.setParam(config.getParam());
				con.setValue(config.getValue());
				con.setComment(config.getComment());
				newConfigs.add(con);
			}
			if (!CollectionUtils.isEmpty(newConfigs)) {
				this.saveBatch(newConfigs);
			}else {
				throw new MarkException(ResponseCode.INIT_PROJECT_NO_CONFIG_PROPERTIES.toString());
			}
		} else {
			throw new Exception();
		}
        return ResponseCode.SUCCESS;
    }
}
